package com.atguigu.service.eud_teacher.edu_subject.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.*;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.exceptionhandler.GuliException;
import com.atguigu.service.eud_teacher.edu_subject.service.VideoService;
import com.atguigu.service.eud_teacher.edu_subject.utils.VideoPropertiesUtils;
import com.atguigu.service.eud_teacher.edu_subject.utils.initDefaultAcsClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service("videoService")

public class VideoServiceImpl implements VideoService {


    @Override
    public HashMap<String, Object> uploadVideo(MultipartFile file) {

        try {
            String accessKeyId = VideoPropertiesUtils.KEY_ID;
            String accessKeySecret = VideoPropertiesUtils.KEY_SECRET;
            //上传之后的名字
            String title = file.getName();
            //原始名字
            String fileName = file.getOriginalFilename();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            // 生成上传文件名
            title = sdf.format(new Date()) + suffixName;
            InputStream inputStream = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            String videoId = response.getVideoId();

            //初始化
            DefaultAcsClient client = initDefaultAcsClient.initVodClient(accessKeyId,
                    accessKeySecret);
            //请求信息,地址
            GetPlayInfoRequest requestPlayInfo = new GetPlayInfoRequest();
            requestPlayInfo.setVideoId(videoId);
            //请求信息，凭证
            GetVideoPlayAuthRequest requestAuth = new GetVideoPlayAuthRequest();
            requestAuth.setVideoId(videoId);
            //响应接受请求的内容
            GetPlayInfoResponse responsePlayInfo = new GetPlayInfoResponse();
            responsePlayInfo = client.getAcsResponse(requestPlayInfo);

            GetVideoPlayAuthResponse responseAuth = new GetVideoPlayAuthResponse();
            responseAuth = client.getAcsResponse(requestAuth);
            //获取相应信息
            List<GetPlayInfoResponse.PlayInfo> playInfoList = responsePlayInfo.getPlayInfoList();
            String playUrl;
            String titleBase;
            String playAuth;
            HashMap<String, Object> map = new HashMap<>();
            //播放地址
            for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
                map.put("playUrl", playInfo.getPlayURL());
                map.put("titleBase", responsePlayInfo.getVideoBase().getTitle());
                map.put("playAuth", responseAuth.getPlayAuth());
            }
            map.put("videoId", videoId);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void deleteVideos(String id) {
        try {
            String accessKeyId = VideoPropertiesUtils.KEY_ID;
            String accessKeySecret = VideoPropertiesUtils.KEY_SECRET;
            DefaultAcsClient client = initDefaultAcsClient.initVodClient(accessKeyId, accessKeySecret);
            DeleteVideoRequest request = new DeleteVideoRequest();
            //支持传入多个视频ID，多个用逗号分隔
            request.setVideoIds(id);
            DeleteVideoResponse response = new DeleteVideoResponse();
            response = client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteForBatch(List videoIdList) {
        try {
            String accessKeyId = VideoPropertiesUtils.KEY_ID;
            String accessKeySecret = VideoPropertiesUtils.KEY_SECRET;
            DefaultAcsClient client = initDefaultAcsClient.initVodClient(accessKeyId, accessKeySecret);

            DeleteVideoRequest request = new DeleteVideoRequest();
            String idsList = StringUtils.join(videoIdList.toArray(), ",");
            //支持传入多个视频ID，多个用逗号分隔
            request.setVideoIds(idsList);
            DeleteVideoResponse response = new DeleteVideoResponse();
            response = client.getAcsResponse(request);
        } catch (ClientException e) {
            throw new GuliException(20001, "视频删除失败");
        }
    }

    //根据vid获取凭证
    @Override
    public String getAuth(String videoSourceId) {
       try {
           //获取阿里云存储相关常量
           String accessKeyId = VideoPropertiesUtils.KEY_ID;
           String accessKeySecret = VideoPropertiesUtils.KEY_SECRET;
           //初始化
           DefaultAcsClient client = initDefaultAcsClient.initVodClient(accessKeyId,
                   accessKeySecret);
           //请求
           GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
           //播放凭证默认时效为100秒（最大为3000秒），只能用
           // 于获取指定视频的播放地址，不能混用或重复使用。
           // 如果凭证过期则无法获取播放地址，需要重新获取凭证。
           request.setAuthInfoTimeout(300L);
           request.setVideoId(videoSourceId);
           //响应
           GetVideoPlayAuthResponse response = client.getAcsResponse(request);
           //得到播放凭证
           String playAuth = response.getPlayAuth();
           //返回结果
           return playAuth;
       }catch (Exception e){
           throw  new GuliException(20001,"获取凭证失败");
       }
    }

//    public static void main(String[] args) {
//        List idsList = new ArrayList();
//        idsList.add(1111);
//        idsList.add(2222);
//        System.out.println(idsList);
//
//        List<Integer> idsLists = new ArrayList();
//        idsLists.add(3333);
//        idsLists.add(4444);
//        System.out.println(idsLists);
//
//    }
}